<template>
	<div class="main">
		<div>
			<div>
				<div>
					<img src="@/assets/images/wechat/student/battle/1.png">
				</div>
				<div>
					<img src="@/assets/images/wechat/student/battle/2.png">
				</div>
			</div>
			<div>
				<div>{{tip}}</div>
				<div>
					<div>
						<div>
							<img v-if="leftInfoData.avatar" :src="leftInfoData.avatar">
							<img v-else src="@/assets/images/wechat/student/battle/3.png">
						</div>
						<div>{{leftInfoData.name}}</div>
					</div>
					<div>
						<div>
							<img src="@/assets/images/wechat/student/battle/pk.png">
						</div>
						<div>
							<div>
								<img src="@/assets/images/wechat/student/battle/6.png">
							</div>
							<div>{{countDownData.format}}</div>
						</div>
					</div>
					<div>
						<div>
							<img v-if="rightInfoData.avatar" :src="rightInfoData.avatar">
							<img v-else src="@/assets/images/wechat/student/battle/5.png">
						</div>
						<div>{{rightInfoData.name}}</div>
					</div>
				</div>
			</div>
			<div>
				<div v-if="contestData.status==0" @click="closeBattle()">
					<div>
						<img src="@/assets/images/wechat/student/battle/giveup.png">
					</div>
					<div>放弃</div>
				</div>
				<div class="share" :data-clipboard-text="'https://sclfront.lawguanjia.com/#/wechatstudent/battle?contestId='+contestData.id" v-if="studentData.type==0&&contestData.id&&contestData.status==0" @click="share()">
					<div>
						<img src="@/assets/images/wechat/student/battle/invite.png">
					</div>
					<div>邀请</div>
				</div>
			</div>
			<div v-show="studentData.type==0&&contestData.isShow">
				<div>
					<img src="@/assets/images/wechat/student/battle/10.png">
				</div>
				<select>
					<option v-for="(item,index) in difficultyList" :value="item.id" :key="index">{{item.name}}</option>
				</select>
			</div>
			<div v-show="contestData.isShow" @click="saveContest()">
				<div>
					<img src="@/assets/images/wechat/student/battle/bk.png">
				</div>
				<div>
					<div>
						<img src="@/assets/images/wechat/student/battle/11.png">
					</div>
					<div>{{studentData.type==0?'创建队伍':'接受挑战'}}</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import router from '@/router/index'
	import Clipboard from 'clipboard'
	import { selectAllByParentId } from '@/api/datadictionary'
	import { findStudentByToken,findStudentById } from '@/api/student'
	import { findContest,findContestById,insertContest,updateContestById } from '@/api/contest'
	
	export default {
		components: {
			
		},
		data() {
			return {
				websocket: null,
				timer: null,
				countDownData: {
					format: '--:--',
					second: 600
				},
				tip: '-----',
				contestData: {
					id: '',
					senderId: 0,
					recipientId: 0,
					status: 0,
					createTime: 0,
					isShow:true
				},
				leftInfoData:{
					id: '',
					avatar: '',
					name:'----',
				},
				rightInfoData:{
					id: '',
					avatar: '',
					name:'----'
				},
				studentData: {
					id: '',
					avatar: '',
					name:'',
					type: 0 // 0邀请人 1参与人
				},
				difficultyList: []
			}
		},
		created:async function() {
			//传入参数
			this.contestData.id=this.$route.query.contestId
			
			/**********查询自己的信息*********/
			const ajaxData1 = {}
			const resultData1 = await findStudentByToken(ajaxData1)
			if(resultData1.code==200){
				if(resultData1.data.firstLogin){
					router.push({path:"/wechatstudent/studentinfo"})
					return
				}
				this.studentData.id = resultData1.data.id
				this.studentData.avatar = resultData1.data.avatar
				this.studentData.name = resultData1.data.name
			} else {
				return
			}
			
			//查询难度字典
			this.selectDifficulty()
			
			/***********查询比赛信息****************/
			if(this.contestData.id){
				//被邀请进来的，检查对应的比赛的状态
				const ajaxData = {}
				ajaxData.id = this.contestData.id
				const resultData = await findContestById(ajaxData)
				if(resultData.code==200){
					this.contestData.id=resultData.data.id
					this.contestData.senderId=resultData.data.senderId
					this.contestData.recipientId=resultData.data.recipientId
					this.contestData.status=resultData.data.status
					this.contestData.createTime=resultData.data.createTime
					this.contestData.lockTime=resultData.data.lockTime
					this.contestData.systemTime=resultData.data.systemTime
				} else {
					this.contestData.id = '' //记录不在了清空掉
				}
			} else {
				//正常进入，检查是否存在创建过且锁定的比赛
				const ajaxData = {}
				ajaxData.senderId = this.studentData.id
				ajaxData.status = 1
				const resultData = await findContest(ajaxData)
				if(resultData.code==200){
					//判断是否有正在进行的排位赛
					if(resultData.data.robot) {
						this.$dialog.alert({
						  title: '创建失败',
						  message: '你有正在进行的排位赛',
						  confirmButtonText: '确认',
						}).then(() => {
							router.replace("/wechatstudent/stucenter")
						})
						return
					}
					this.contestData.id=resultData.data.id
					this.contestData.senderId=resultData.data.senderId
					this.contestData.recipientId=resultData.data.recipientId
					this.contestData.status=resultData.data.status
					this.contestData.createTime=resultData.data.createTime
					this.contestData.lockTime=resultData.data.lockTime
					this.contestData.systemTime=resultData.data.systemTime
				}
			}
			
			/*********可能情况**********/
			
			//如果比赛不存在就需要创建
			if(!this.contestData.id){
				this.tip = '请创建队伍'
				this.leftInfoData = this.studentData
				this.studentData.type = 0 //我要作为创建人
				this.initWebsocket()
				return
			}
			
			//如果比赛结束
			if(this.contestData.status==2){
				this.tip = '比赛已结束'
				if(this.contestData.senderId==this.studentData.id||this.contestData.recipientId==this.studentData.id){
					// 跳转到结束页面
					router.replace({path: "/wechatstudent/balance",query: {id:this.contestData.id}})
				} else {
					// 比赛已结束
					this.$dialog.alert({
					  title: '提示',
					  message: '比赛已结束',
					  confirmButtonText: '确认',
					}).then(() => {
						router.replace("/wechatstudent/stucenter")
					})
				}
				return
			}
			
			//如果比赛过期
			if(this.contestData.status==0&&(this.contestData.systemTime - this.contestData.createTime > 600)){
				this.tip = '请创建队伍'
				this.leftInfoData = this.studentData
				this.studentData.type = 0 //我要作为创建人
				this.initWebsocket()
				this.contestData.status=0
				//自动结束该场比赛
				const ajaxData = {}
				ajaxData.id = this.contestData.id
				ajaxData.status = 2
				const resultData = await updateContestById(ajaxData)
				return
			}
			
			
			//被锁定
			if(this.contestData.status==1){
				if(this.contestData.senderId==this.studentData.id||this.contestData.recipientId==this.studentData.id){
					this.tip = '准备比赛,请不要随意离开'
					this.countDownData.second = 5 - (this.contestData.systemTime - this.contestData.lockTime)
					// 跳转到比赛页面，这里逻辑还要处理，比如时间过期了，跳转后应该跳到第几题
					if(this.countDownData.second < 0&&this.countDownData.second >= -100){
						router.replace({path:"/wechatstudent/answer",query:{id:this.contestData.id}})
					}else if(this.countDownData.second < -100){
						router.replace({path:"/wechatstudent/balance",query:{id:this.contestData.id}})
					} else {
						if(this.contestData.senderId==this.studentData.id){
							//1.本人是创建者
							this.leftInfoData = this.studentData
							this.studentData.type = 0
							this.findStudentById(this.contestData.recipientId)
						} else {
							//1.本人是参与者
							this.rightInfoData = this.studentData
							this.studentData.type = 1
							this.findStudentById(this.contestData.senderId)
						}
						this.contestData.isShow = false
						this.countDown()
					}
				} else {
					// 本人来晚了
					this.$dialog.alert({
					  title: '提示',
					  message: '该队伍人已满',
					  confirmButtonText: '确认',
					}).then(() => {
						router.replace("/wechatstudent/stucenter")
					})
				}
				return
			}
			
			//未被锁定
			if(this.contestData.status==0){
				if(this.contestData.senderId==this.studentData.id){
					//1.本人是创建者
					this.tip = '请邀请对手对战'
					this.leftInfoData = this.studentData
					this.studentData.type = 0
					this.contestData.isShow = false
				} else {
					//1.本人是参与者
					this.tip = '请点击接受挑战'
					this.rightInfoData = this.studentData
					this.studentData.type = 1
					this.findStudentById(this.contestData.senderId)
					console.log(this.contestData.isShow)
				}
			}
			this.countDownData.second = 600 - (this.contestData.systemTime - this.contestData.createTime)
			this.countDown()
			this.initWebsocket()
		},
		beforeMount: function() {
	
		},
		mounted: function() {
			
		},
		beforeUnmount: function() {
			//每次进来先清理下定时器
			clearInterval(this.timer)
		},
		methods: {
			async selectDifficulty() {
			  const ajaxData = {}
			  ajaxData.parentId = "d32575c1ef124b3192bb06448951efee"
			  const resultData = await selectAllByParentId(ajaxData)
			  if (resultData.code === 200) {
			    this.difficultyList = resultData.data
			  }
			},
			async findStudentById(id) {
			  const ajaxData = {}
			  ajaxData.id = id
			  const resultData = await findStudentById(ajaxData)
			  if (resultData.code === 200) {
			    if(this.studentData.type == 0){
					this.rightInfoData = resultData.data
				}else{
					this.leftInfoData = resultData.data
				}
			  }
			},
			async saveContest(){
				if(this.studentData.type == 0){
					this.insertContest()
				}else{
					const ajaxData = {}
					ajaxData.id = this.contestData.id
					const resultData1 = await findContestById(ajaxData)
					if(resultData1.status==1){
						this.$dialog.alert({
						  title: '提示',
						  message: '加入失败，队伍已满',
						  confirmButtonText: '确认',
						}).then(() => {
							router.replace("/wechatstudent/stucenter")
						})
						return
					}
					ajaxData.recipientId = this.studentData.id
					ajaxData.status = 1
					const resultData2 = await updateContestById(ajaxData)
					if (resultData2.code === 200) {
					  //加入成功,发送信息给创建者
						this.tip = '加入成功，倒计时5s'
						this.contestData.isShow = false
						this.countDownData.second = 5
						this.contestData.status = 1
						const data = {}
						data.recipientId = 'student' + this.leftInfoData.id
						data.code = 100
						data.messageContent = this.studentData.id
						this.websocketSend(JSON.stringify(data))
					}
				}
			},
			async insertContest() {
			  const ajaxData = {}
			  const resultData = await insertContest(ajaxData)
			  if (resultData.code === 200) {
				this.tip = '队伍创建成功，请邀请对手对战'
			    this.contestData.id = resultData.data
				this.contestData.isShow = false
				this.countDown()
			  } else{
				  this.$dialog.alert({
				    title: '提示',
				    message: resultData.msg,
				    confirmButtonText: '确认',
				  }).then(() => {
				  	router.replace("/wechatstudent/stucenter")
				  })
			  }
			},
			async closeBattle() {
				clearInterval(this.timer)
				console.log("放弃")
				if(this.contestData.status==1){
					this.tip = '队伍已锁定无法放弃'
					return
				}
				if(this.studentData.type==0&&this.contestData.id){
					const ajaxData = {}
					ajaxData.id = this.contestData.id
					ajaxData.status = 2
					const resultData = await updateContestById(ajaxData)
				}
				router.push({path:"/wechatstudent/stucenter"})
			},
			countDown() {
				this.timer = setInterval(()=>{
					this.countDownData.second--
					console.log(this.countDownData.second)
					let format = parseInt(this.countDownData.second / 60)
					format = format +':'+ (this.countDownData.second - format*60)
					this.countDownData.format = format
					if(this.countDownData.second==0){
						clearInterval(this.timer)
						if(this.contestData.status==0){
							this.$dialog.alert({
							  title: '提示',
							  message: '长时间匹配不到对手，强制离开',
							  confirmButtonText: '确认',
							}).then(() => {
								router.replace("/wechatstudent/stucenter")
							})
						} else{
							router.replace({path:"/wechatstudent/answer",query:{id:this.contestData.id}})
						}
					}
				},1000)
			},
			share(){
				const clipboard = new Clipboard('.share')
				clipboard.on('success', e => {
					alert('分享链接已复制，请分享给好友')
					//  释放内存
					clipboard.destroy()
				})
				clipboard.on('error', e =>{
				    // 不支持复制
				    alert('该浏览器不支持复制')
				    // 释放内存
				    clipboard.destroy()
				})
			},
			initWebsocket() { //初始化weosocket
				let wsUrl = process.env.VUE_APP_BASE_WS+"/openApi/websocket/" + 'student' + this.studentData.id
				this.websocket = new WebSocket(wsUrl);
				this.websocket.onmessage = this.websocketOnMessage
				this.websocket.onopen = this.websocketOnOpen
				this.websocket.onerror = this.websocketOnError
				this.websocket.onclose = this.websocketOnClose
			},
			websocketOnOpen() { //连接建立之后执行send方法发送数据
				console.log("连接成功等待对方上线")
			},
			//连接建立失败
			websocketOnError() {
				console.log("连接失败请稍后再试")
				this.tip = "网络故障"
			},
			//数据接收
			async websocketOnMessage(e) {
				const data = JSON.parse(e.data)
				console.log(data)
				if(data.code==100){
					this.tip = '对战队伍组队成功，30s后开始对战'
					const ajaxData = {}
					ajaxData.id = data.messageContent
					const resultData = await findStudentById(ajaxData)
					if(resultData.code==200){
						this.rightInfoData=resultData.data
						this.countDownData.second=30
						this.contestData.status=1
					}
				}
				
			},
			//数据发送
			websocketSend(data) {
				this.websocket.send(data);
			},
			//关闭
			websocketOnClose() {
				console.log("连接已经断开")
				this.tip = "你已经离开队伍"
			}
		}
	}
</script>

<style lang="scss" scoped>
	.main{
		width: 100%;
		height: 100vh;
		overflow: auto;
		background-image: url(../../../../assets/images/wechat/student/public/bg.jpg);
		background-size: cover;
		background-position: center;
		//background-color: #670914;
		>div:nth-child(1){
			overflow: hidden;
			margin-top:34px;
			margin-left:16px;
			margin-right:16px;
			>div:nth-child(1){
				position: relative;
				>div:nth-child(1){
					width: 100%;
					>img{
						width:100%;
					}
				}
				>div:nth-child(2){
					width: 100%;
					position: absolute;
					top:0;
					left:0;
					>img{
						width:100%;
					}
				}
			}
			>div:nth-child(2){
				margin-top:24px;
				>div:nth-child(1){
					text-align: center;
					font-size: 14px;
					font-weight: normal;
					color: #FFFFFF;
				}
				>div:nth-child(2){
					margin-top:30px;
					display:flex;
					justify-content: space-around;
					>div:nth-child(1),>div:nth-child(3){
						>div:nth-child(1){
							width:63px;
							height:63px;
							margin: auto;
							overflow:hidden;
							border-radius: 50%;
							>img{
								width:100%;
							}
						}
						>div:nth-child(2){
							font-size: 12px;
							color: #FFFFFF;
							margin-top:6px;
							text-align: center;
						}
					}
					>div:nth-child(2){
						margin-top:8px;
						>div:nth-child(2){
							display:flex;
							align-items: center;
							justify-content: center;
							background-color: #BA7C1A;
							width: 58px;
							margin:auto;
							margin-top:12px;
							height:20px;
							>div:nth-child(2){
								margin-left:3px;
								font-size:12px;
								color:#FFFFFF;
							}
						}
					}
				}
			}
			>div:nth-child(3){
				display: flex;
				justify-content: center;
				margin-top:48px;
				>div{
					>div:nth-child(2){
						margin-top:7px;
						font-size: 14px;
						font-weight: normal;
						color: #FFFFFF;
						text-align: center;
					}
				}
				>div:nth-child(1){
					margin-right:70px;
					>div:nth-child(2){
						margin-top:9px;
					}
				}
			}
			>div:nth-child(4){
				width:100px;
				margin:auto;
				margin-top:22px;
				position: relative;
				display: flex;
				background: url(../../../../assets/images/wechat/student/battle/bk.png)no-repeat;
				>div{
					
					margin-left:8px;
					margin-top:8px;
				}
				>select{
					width:100%;
					outline: none;
					line-height:26px;
					height:25px;
					font-size: 15px;
					text-align-last:center;
					appearance: none;
					color:#FFFFFF;
					background-color: rgba(0,0,0,0);
					border-radius:5px;
					border: 0px;
				}
			}
			>div:nth-child(5){
				width:100px;
				margin:auto;
				margin-top:10px;
				position: relative;
				>div:nth-child(1){
					>img{
						wdith:100%;
					}
				}
				>div:nth-child(2){
					position: absolute;
					left:0;
					top:0;
					padding-left:8px;
					padding-top:2px;
					display:flex;
					align-items: center;
					>div:nth-child(2){
						margin-left:5px;
						color:#FFFFFF;
						font-size: 15px;
					}
				}
			}
		}
	}
</style>
